﻿using DapperExtensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WeChatParking.Web.UrlAuthorize;

namespace WeChatParking.Web.Controllers
{
    public class ReportController : AdminBaseController
    {
        public ActionResult Summary()
        {
            return View();
        }

        /// <summary>
        /// 首页当天汇总数据
        /// </summary>
        /// <returns></returns>
        public ActionResult SummaryData()
        {
            var user = base.LoginUser;
            if (user == null)
                return Redirect("~/Admin/Login");
            int enterId = user.UserName == "admin" ? 0 : user.EnterpriseID;//是超级管理员就是获取所有数据
            decimal PayAmount = 0M;
            int PayCount = 0;
            int inCount = 0;
            int outCount = 0;
            DateTime beginDate = DateTime.Today;
            var bll = new Core.BLL.Report();
            PayAmount = bll.GetDailyReport(enterId, beginDate, out PayCount, out inCount, out outCount);

            return Json(new
            {
                PayAmount = string.Format("￥{0:N}", PayAmount),
                PayCount = PayCount,
                inCount = inCount,//进场记录数
                outCount = outCount//出场记录数
            });
        }
        public ActionResult RealtimeOrders()
        {
            Entity.OrderQuery summaryData = null;
            var filter = base.GetPageInfo();
            bool asc = filter.asc;
            string where = "where 1=1";

            short payStatus = 3;
            if (payStatus > 0)
            {
                where += String.Format("  and o.pay_status = '{0}' ", payStatus);
            }
            where += String.Format("  and o.pay_time >= '{0}' ", DateTime.Now.AddDays(-1));
            var user = base.LoginUser;
            if (user == null)
                return Redirect("~/Admin/Login");
            user.EnterpriseID = user.UserName == "admin" ? 0 : user.EnterpriseID;//是超级管理员就是获取所有数据
            if (user.EnterpriseID > 0)
            {
                where += String.Format("  and o.EnterpriseID = '{0}' ", user.EnterpriseID);
            }
            Core.BLL.Order_info bll = new Core.BLL.Order_info();
            if (string.IsNullOrWhiteSpace(filter.sort)) filter.sort = "pay_time";

            var data = bll.QueryOrderList(true, where, filter, out summaryData);
            return base.ToGridJson(data);
        }

        public FileResult Download(string file, string filename)
        {
            string absoluFilePath = Server.MapPath("~/Download/" + Server.UrlDecode(file));
            return File(new System.IO.FileStream(absoluFilePath, System.IO.FileMode.Open), "application/octet-stream", filename);
        }

        #region 支付报表
        public ActionResult OrderReport()
        {
            var bll = new Core.BLL.Enterprise();
            int EnterpriseID = base.GetEnterpriseID();//是超级管理员就是获取所有数据//是超级管理员就是获取所有数据
            var list = bll.EnterpriseQuery(EnterpriseID); ;
            if (EnterpriseID == 0)
                list.Add(new Entity.Enterprise() { ID = 0, Enterprise_Code = "0", Enterprise_Name = "全部" });
            var EnterpriseList = list.OrderBy(t => t.ID).ToList();
            EnterpriseList = EnterpriseList.Where(t => t.Enterprise_FCode != "0").ToList();
            ViewBag.EnterpriseList = EnterpriseList;
            return View();
        }
        [HttpPost]
        public ActionResult OrderDataReport()
        {
            var data = this.GetOrderData();
            Decimal pay_fee_Sum = data.DataList.Sum(t => t.pay_fee);
            Decimal UnionPay_fee_Sum = data.DataList.Sum(t => t.UnionPay_fee);
            Decimal Weixin_fee_Sum = data.DataList.Sum(t => t.Weixin_fee);
            Decimal Alipay_fee_Sum = data.DataList.Sum(t => t.Alipay_fee);
            Decimal Tonglian_fee_Sum = data.DataList.Sum(t => t.Tonglian_fee);
            Decimal XJPay_fee_Sum = data.DataList.Sum(t => t.XJPay_fee);
            return base.ToGridJson(data, new
            {
                order_id = string.Format("合计： 共 {0} 笔订单", data.Total),
                pay_fee = pay_fee_Sum,
                UnionPay_fee = UnionPay_fee_Sum,
                Weixin_fee = Weixin_fee_Sum,
                Alipay_fee = Alipay_fee_Sum,
                Tonglian_fee = Tonglian_fee_Sum,
                XJPay_fee = XJPay_fee_Sum
            });
        }
        public Entity.PageList<Entity.Report.Order_Report> GetOrderData()
        {
            DateTime benginTime = DateTime.Parse(DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd"));
            DateTime endTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
            int EnterpriseID = base.GetEnterpriseID();
            Core.BLL.Order_info bll = new Core.BLL.Order_info();
            if (!string.IsNullOrWhiteSpace(Request.Form["paytime_begin"]))
            {
                benginTime = Util.Conv.ToDate(Request.Form["paytime_begin"]);
            }
            if (!string.IsNullOrWhiteSpace(Request.Form["paytime_end"]))
            {
                endTime = Util.Conv.ToDate(Request.Form["paytime_end"]).AddDays(1);
            }
            if (!string.IsNullOrWhiteSpace(Request.Form["CCEnterpriseID"]))
            {
                EnterpriseID = Util.Conv.ToShort(Request.Form["CCEnterpriseID"]);
            }
            endTime = endTime.AddDays(1).AddSeconds(-1);
            var list = bll.GetCurrentMeals(benginTime, endTime, EnterpriseID);

            Entity.PageList<Entity.Report.Order_Report> data = new Entity.PageList<Entity.Report.Order_Report>();
            data.DataList = list;
            data.Page = 1;
            data.Total = list.Count();
            data.TotalPage = 1;
            return data;

        }
        public ActionResult DownloadOrderData()
        {
            var data = this.GetOrderData();
            if (data.Total == 0)
                return Fail("无订单数据");

            if (data.Total >= 65535)
                return Fail("数据量太多（超出65535），请缩小查询范围");
            #region 生成文件
            string filePath = Server.MapPath("~/Download");
            if (!System.IO.Directory.Exists(filePath))
                System.IO.Directory.CreateDirectory(filePath);
            string fileName = string.Format("支付报表_{0:yyyyMMddHHmm}.csv", DateTime.Now);
            string tempFileName = System.Guid.NewGuid().ToString() + ".csv";
            var fileStream = System.IO.File.Create(System.IO.Path.Combine(filePath, tempFileName));
            string rowFmt = "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}";
            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(fileStream, System.Text.Encoding.UTF8);
            streamWriter.WriteLine(rowFmt, "订单号", "姓名", "车牌号", "物业名称", "停车场名称", "支付金额", "云闪付", "微信支付", "支付宝支付", "通联支付", "现金支付", "支付时间", "创建时间");
            foreach (var d in data.DataList)
                streamWriter.WriteLine(rowFmt, d.order_id, d.Wxuser_name, d.car_no, d.Enterprise_Name,
                   d.CCEnterprise_Name, d.pay_fee, d.UnionPay_fee, d.Weixin_fee, d.Alipay_fee, d.Tonglian_fee, d.XJPay_fee, this.RendertDate(d.pay_time), this.RendertDate(d.create_time));
            streamWriter.Flush();
            streamWriter.Close();
            fileStream.Close();
            #endregion
            return OK(string.Format("/Report/Download?file={0}&filename={1}", Server.UrlEncode(tempFileName), Server.UrlEncode(fileName)));
        }
        private string RendertDate(DateTime? date)
        {
            return date.HasValue ? date.Value.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty;
        }
        #endregion

        [UrlAuthorize]
        public ActionResult SettlementReport()
        {
            var bll = new Core.BLL.Enterprise();
            int EnterpriseID = base.GetEnterpriseID();//是超级管理员就是获取所有数据//是超级管理员就是获取所有数据
            var list = bll.EnterpriseQuery(EnterpriseID); ;
            //if (EnterpriseID == 0)
            //    list.Add(new Entity.Enterprise() { ID = 0, Enterprise_Code = "0", Enterprise_Name = "全部" });
            var EnterpriseList = list.OrderBy(t => t.ID).ToList();
            EnterpriseList = EnterpriseList.Where(t => t.Enterprise_FCode != "0").ToList();
            ViewBag.EnterpriseList = EnterpriseList;
            return View();
        }
        [HttpPost]
        public ActionResult SettlementReportData()
        {
            try
            {
                var data = this.GetSettlementReportData();
                Decimal pay_fee_Sum = data.DataList.Sum(t => t.pay_fee);
                Decimal UnionPay_fee_Sum = data.DataList.Sum(t => t.UnionPay_fee);
                Decimal Weixin_fee_Sum = data.DataList.Sum(t => t.Weixin_fee);
                Decimal Alipay_fee_Sum = data.DataList.Sum(t => t.Alipay_fee);
                Decimal Tonglian_fee_Sum = data.DataList.Sum(t => t.Tonglian_fee);
                Decimal XJPay_fee_Sum = data.DataList.Sum(t => t.XJPay_fee);
                return base.ToGridJson(data, new
                {
                    order_id = string.Format("合计： 共 {0} 笔记录", data.Total),
                    pay_fee = pay_fee_Sum,
                    UnionPay_fee = UnionPay_fee_Sum,
                    Weixin_fee = Weixin_fee_Sum,
                    Alipay_fee = Alipay_fee_Sum,
                    Tonglian_fee = Tonglian_fee_Sum,
                    XJPay_fee = XJPay_fee_Sum
                });
            }
            catch (Exception ex)
            {
                WeChatParking.Core.LogHelper.Error(ex, "查询营也结算表");
                Entity.PageList<Entity.OrderQuery> data = new Entity.PageList<Entity.OrderQuery>();
                return base.ToGridJson(data, new
                {
                    order_id = string.Format("合计： 共 {0} 笔订单", 0),
                    pay_fee = 0,
                    real_fee = 0,
                    total_fee = 0
                });
            }
        }
        public Entity.PageList<Entity.Report.SettlementReport> GetSettlementReportData()
        {
            DateTime benginTime = DateTime.Parse(DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd"));
            DateTime endTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
            int EnterpriseID = base.GetEnterpriseID();
            Core.BLL.Order_info bll = new Core.BLL.Order_info();
            if (!string.IsNullOrWhiteSpace(Request.Form["paytime_begin"]))
            {
                benginTime = Util.Conv.ToDate(Request.Form["paytime_begin"]);
            }
            if (!string.IsNullOrWhiteSpace(Request.Form["paytime_end"]))
            {
                endTime = Util.Conv.ToDate(Request.Form["paytime_end"]).AddDays(1);
            }
            if (!string.IsNullOrWhiteSpace(Request.Form["CCEnterpriseID"]))
            {
                EnterpriseID = Util.Conv.ToShort(Request.Form["CCEnterpriseID"]);
            }
            else
            {
                EnterpriseID = 3;
            }
            //endTime = endTime.AddDays(1).AddSeconds(-1);
            TimeSpan ts = endTime - benginTime;
            int num = ts.Days;
            var list = bll.GetSettlementReport(num, benginTime, endTime, EnterpriseID);

            Entity.PageList<Entity.Report.SettlementReport> data = new Entity.PageList<Entity.Report.SettlementReport>();
            data.DataList = list;
            data.Page = 1;
            data.Total = list.Count();
            data.TotalPage = 1;
            return data;
        }

        public ActionResult DownloadSettlementReport()
        {
            var data = this.GetSettlementReportData();
            if (data.Total == 0)
                return Fail("无订单数据");

            if (data.Total >= 65535)
                return Fail("数据量太多（超出65535），请缩小查询范围");
            #region 生成文件
            string filePath = Server.MapPath("~/Download");
            if (!System.IO.Directory.Exists(filePath))
                System.IO.Directory.CreateDirectory(filePath);
            string fileName = string.Format("支付报表_{0:yyyyMMddHHmm}.csv", DateTime.Now);
            string tempFileName = System.Guid.NewGuid().ToString() + ".csv";
            var fileStream = System.IO.File.Create(System.IO.Path.Combine(filePath, tempFileName));
            string rowFmt = "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}";
            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(fileStream, System.Text.Encoding.UTF8);
            streamWriter.WriteLine(rowFmt, "停车场名称", "支付金额", "云闪付", "微信支付", "支付宝支付", "通联支付", "现金支付", "日期");
            foreach (var d in data.DataList)
                streamWriter.WriteLine(rowFmt,
                   d.CCEnterprise_Name, d.pay_fee, d.UnionPay_fee, d.Weixin_fee, d.Alipay_fee, d.Tonglian_fee, d.XJPay_fee, this.RendertDate(d.Riqi));
            streamWriter.Flush();
            streamWriter.Close();
            fileStream.Close();
            #endregion
            return OK(string.Format("/Report/Download?file={0}&filename={1}", Server.UrlEncode(tempFileName), Server.UrlEncode(fileName)));
        }
    }
}
